#!/usr/bin/env python

# this script is to mass-rename a bunch of .fcs files
# it takes a csv file (arg 1) with these headers:
#   Well,Gene,Drug,Concentration
#   A1,PEX11,Cerulenin,1.92
#   ...

# as well as a time (arg 2), and renames the files:
# Specimen_001_A1_A01.fcs -> 2011-11-15_PEX11_Cerulenin_1.92_t0.fcs


import csv
import os
import re
import sys

import datetime # to get today's date in iso format

today = datetime.date.today().isoformat()

# regular expression to capture well number
spec_re = re.compile(r'Specimen_(?:\d+)_([A-H]\d+)_(?:[A-H]\d+)\.fcs', flags=re.I)

mapping = sys.argv[1]
timepoint = sys.argv[2]

with open(mapping) as f:
    print f.readline() # only if you have headers
    rdr = csv.reader(f)
    # list comprehension: make a dictionary for each 
    well_map = dict((row[0], tuple(r or 'None' for r in row[1:])) for row in rdr)

print well_map.keys()

for fsc_f in sys.argv[3:]:
    v = well_map[spec_re.match(os.path.basename(fsc_f)).group(1)]
    
    p = os.path.dirname(fsc_f)
    print "rename %s to %s_%s_%s_%s_t%s.fcs" % ((fsc_f, today,) + v + (timepoint,))
    # os.rename(fsc_f, os.path.join(p, "%s_%s_%s_%s_t%s.fcs" % ((today,) + v)))
